package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//登录核验过滤器---检查用户是否已经完成登录
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //创建路径匹配器
    AntPathMatcher pathMatcher = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        log.info("拦截器已经启动...");
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //        1. 获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求:{}",requestURI);
//        long threadId = Thread.currentThread().getId();
//        log.info("doFilter线程id:"+threadId);
        //定义不需要处理的请求路径
        String[] uris = {
                "/employee/login",
                "/employee/loginout",
                "/backend/**",
                "/front/**",
                "/common/**"
        };
        //2.判断本次请求是否需要处理
        boolean result = checkPath(uris, requestURI);
        //3.判断本次请求不需要处理直接放行
        if (result) {
            log.info("本次拦截请求{}无需处理,直接放行",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //4.判断登录状态,如果已经登录直接放行

        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已经登录,用户id为:{}",request.getSession().getAttribute("employee"));
            //在已经判定登陆后放行之前获取用户id
            Long userId = (Long) request.getSession().getAttribute("employee");
            //将用户id放入ThreadLocal封装工具类
            BaseContext.setThreadId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //5.判断登录状态为未登录,返回结果
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    //判断请求路径与无需处理路径是否匹配
    public boolean checkPath(String[] uris,String requestUri) {
        //调用路径匹配器的方法
        for (String uri : uris) {
//            return pathMatcher.match(uri, requestUri);
            boolean match = pathMatcher.match(uri, requestUri);
            if(match){
                return true;
            }
        }
        return false;
    }
}
